package cn.szzsi.common.kit;


import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * Created by admin on 2017/7/25.
 */
public class EHcacheUtil {
    public static final String RESOURCE_MENU="resourceMenu";
    public static final String PLATEFORM_RESOURCE_MENU="platefromResourceMenu";
    public static final String PLATEFORM_CONFIG="plateformConfig";//核心平台商城配置
    private static final String path = "ehcache.xml";

    private static EHcacheUtil ehcacheUtil;

    private CacheManager manager;

    private EHcacheUtil(){
        manager = CacheManager.create(EHcacheUtil.class.getResourceAsStream(path));
    }

    public synchronized static EHcacheUtil getInstance(){
        if(ehcacheUtil == null){
            return new EHcacheUtil();
        }
        return ehcacheUtil;
    }

    public void put(String cacheName, String key, Object value) {
        Cache cache = getCache(cacheName);
        Element element = new Element(key, value);
        cache.put(element);
    }

    public Object get(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        Element element = cache.get(key);
        return element == null ? null : element.getObjectValue();
    }

    public void remove(String cacheName, String key) {
        Cache cache = manager.getCache(cacheName);
        cache.remove(key);
    }

    public Cache getCache(String cacheName){
        Cache cache = manager.getCache(cacheName);
        if(cache == null){
            throw new RuntimeException("根据cacheName="+cacheName+"无法获取到对于的cache!请检查配置文件"+path);
        }
        return cache;
    }

}
